<template>
  <div class="login-container">
    <van-nav-bar title="登录">
      <template #left>
        <img src="@/assets/image/logo.png" class="logo"/>
      </template>
    </van-nav-bar>
    <van-form @submit="onSubmitFn">
      <van-field
        v-model="formLogin.mobile"
        type="tel"
        label="手机号"
        placeholder="请输入手机号"
        required
        :rules="[
          { required: true, message: '请填写手机号', trigger: 'onChange' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入合法的手机号', trigger: 'onChange' }
        ]"
      />
      <van-field
        v-model="formLogin.code"
        type="password"
        label="验证码"
        placeholder="请输入验证码"
        required
        :rules="[
          { required: true, message: '请填写验证码', trigger: 'onChange' },
          { pattern: /^\d{6}$/, message: '请输入合法的验证码',trigger: 'onChange' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          :loading="loading"
          loading-text="登录中..."
          round
          block
          type="info"
          native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { loginAPI } from '@/api/login'
export default {
  name: 'Login',
  created () {
    console.log('Login Created')
  },
  destroyed () {
    console.log('Login Destroyed')
  },
  data () {
    return {
      // 登录的表单数据
      formLogin: {
        mobile: '13522513531',
        code: '246810' // 默认只能用246810后台规定了
      },
      loading: false // 登录按钮的加载状态，默认值false，表示没有在加载中
    }
  },
  methods: {
    ...mapMutations('user', ['setToken', 'setRefreshToken']),
    // 登录提交
    async onSubmitFn () {
      this.loading = true
      try {
        // 调用接口
        const resp = await loginAPI({
          tel: this.formLogin.mobile,
          pwd: this.formLogin.code
        })
        // 拿token和refresh_token，提交到mutation即可
        const { token, refresh_token: refreshToken } = resp.data
        this.setToken(token)
        this.setRefreshToken(refreshToken)
        this.$toast.success('登录成功')
        this.$router.replace(this.$route.query.redirect || '/layout')
      } catch (e) {
        this.$toast.fail('登录出错')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.logo {
  width: 100px;
  height: 30px;
}
</style>
